<?php

namespace App\Http\Controllers;

use App\Models\ChannelStatistics;
use App\Models\DistributorUser;
use App\Models\OrderInfo;
use App\Models\Payoff;
use App\Models\User;
use App\Services\ProxyService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class DistributionController extends Controller
{
    protected $proxyService;

    public function __construct(ProxyService $proxyService)
    {
        $this->proxyService = $proxyService;
    }

    public function info(Request $request)
    {
        $user_id = Auth::id();
        if ($request->filled('user_id')) {
            $user_id = $request->input('user_id');
        }
        $user_info = User::find($user_id);
        $ids = User::where('invite_userid', $user_id)->pluck('id');
        $order_amount = 0.00;
        if (!empty($ids)) {
            $order_amount = OrderInfo::whereIn('user_id', $ids)->where('status', 1)->sum('amount');
        }
        $income_ratio = DistributorUser::where('user_id', $user_id)->value('income_ratio');
        $data = [
            'user_id' => $user_id,
            'username' => $user_info->username,
            'total_income' => $user_info->total_income,
            'income' => $user_info->income,
            'pay_income' => Payoff::where('user_id', $user_id)->sum('amount'),
            'order_amount' => $order_amount,
            'income_ratio' => $income_ratio . '%'
        ];
        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => $data
        ]);
    }

    public function inviteUserList(Request $request)
    {
        $user_id = Auth::id();
        if ($request->filled('user_id')) {
            $user_id = $request->input('user_id');
        }
        $limit = 10;
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;

        $user = User::find($user_id);
        $count = User::where('invite_userid', $user_id)->count();
        $list = User::where('invite_userid', $user_id)->offset($offset)->limit($limit)->orderBy('id', 'desc')->get();
        foreach ($list as $item) {
            $order_amount = OrderInfo::where('user_id', $item->id)->where('status', 1)->sum('amount');
            $item->order_amount = $order_amount;
            $item->income = $user->total_income;
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list
            ]
        ]);
    }

    public function payoffList(Request $request)
    {
        $user_id = Auth::id();
        if ($request->filled('user_id')) {
            $user_id = $request->input('user_id');
        }
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;
        $user = User::find($user_id);
        $count = Payoff::where('user_id', $user_id)->count();
        $list = Payoff::where('user_id', $user_id)->offset($offset)->limit($limit)->orderBy('id', 'desc')->get();
        foreach ($list as $item) {
            $item->username = $user->username;
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list
            ]
        ]);
    }

    public function userList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;

        $count = DistributorUser::count();
        $list = DistributorUser::offset($offset)->limit($limit)->orderBy('id', 'desc')->get();
        foreach ($list as $item) {
            $user = User::where('id', $item->user_id)->first();
            $item->username = $user->username;
            $item->total_income = $user->total_income;
            $item->income = $user->income;
            $item->payoff = bcsub($user->total_income, $user->income, 2);
            $item->link = 'https://ipxproxy.com/?hz=' . $item->invite_code;
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list
            ]
        ]);
    }

    public function saveUser(Request $request)
    {
        $rules = [
            'user_id' => 'required|exists:users,id',
            'invite_code' => 'required',
            'income_ratio' => 'required|integer'
        ];

        $messages = [
            'user_id.required' => '缺少用户信息',
            'user_id.exists' => '用户不存在',
            'invite_code.required' => '请输入分销参数',
            'income_ratio.required' => '请输入佣金比例',
            'income_ratio.integer' => '佣金比例输入错误',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'errcode' => -1,
                'errmsg' => $errors->first(),
            ]);
        }

        $data = [
            'user_id' => $request->user_id,
            'invite_code' => $request->invite_code,
            'income_ratio' => $request->income_ratio,
            'remark' => $request->remark ?? ''
        ];
        $exist = DistributorUser::where('user_id', $request->user_id)->first();
        if (!empty($exist)) {
            DistributorUser::where('user_id', $request->user_id)->update($data);
        } else {
            DistributorUser::create($data);
            User::where('id', $request->user_id)->update(['is_distributor' => 1]);
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function resetStatus(Request $request)
    {
        $user_id = $request->input('user_id');

        $info = DistributorUser::where('user_id', $user_id)->first();
        if (empty($info)) {
            return response()->json([
                'errcode' => -1,
                'errmsg' => '参数错误'
            ]);
        }

        if ($info->status == 1) {
            $status = 0;
        } else {
            $status = 1;
        }

        DistributorUser::where('user_id', $user_id)->update(['status' => $status]);

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function payoff(Request $request)
    {
        $user_id = $request->input('user_id');
        $amount = $request->input('amount');
        $remark = $request->input('remark', '');

        $info = DistributorUser::where('user_id', $user_id)->first();
        if (empty($info)) {
            return response()->json([
                'errcode' => -1,
                'errmsg' => '无效操作'
            ]);
        }

        $user = User::find($user_id);
        if (bcsub($user->income, $amount, 2) <= '0.00') {
            return response()->json([
                'errcode' => -1,
                'errmsg' => '可结算金额不足'
            ]);
        }

        $data = [
            'user_id' => $user_id,
            'amount' => $amount,
            'remark' => $remark ?? ''
        ];

        DB::beginTransaction();
        try {
            if (Payoff::create($data)) {
                $res = $user->decrement('income', $amount);
                if (empty($res)) {
                    throw new \Exception('增加用户待结算金额失败');
                }
            } else {
                throw new \Exception('创建结算失败');
            }
        } catch (\Exception $e) {
            return response()->json([
                'errcode' => -1,
                'errmsg' => $e->getMessage()
            ]);
        }

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功'
        ]);
    }

    public function channel(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;

        $count = ChannelStatistics::count();
        $list = ChannelStatistics::offset($offset)->limit($limit)->orderBy('user_count', 'desc')->get();

        return response()->json([
            'errcode' => 0,
            'errmsg' => '操作成功',
            'data' => [
                'count' => $count,
                'list' => $list
            ]
        ]);
    }
}
